use std::collections::HashMap;
use std::fs::{create_dir, create_dir_all, File};
use std::io::Write;
use std::path::PathBuf;
use std::{env, io};

// 加载在编译阶段导入DLL文件到程序
const DLL_FILES_BYTE: [(&'static [u8], &str); 2] = [
    /*(include_bytes!("libs/libeay32.dll"), "libeay32.dll"),
    (include_bytes!("libs/libmysql.dll"), "libmysql.dll"),
    (include_bytes!("libs/ssleay32.dll"), "ssleay32.dll"),
    (include_bytes!("libs/zlib1.dll"), "zlib1.dll"),*/
    (
        include_bytes!("libs/vcruntime140_1.dll"),
        "vcruntime140_1.dll",
    ),
    (
        include_bytes!("../../rust/target/release/stock_info_watch.dll"),
        "stock_info_watch.dll",
    ),
];

pub fn generate_dll_list() -> HashMap<String, String> {
    let mut map = HashMap::new();
    for (v, name) in DLL_FILES_BYTE.iter().as_slice() {
        let (name, path) = generate_dll(name, v).unwrap();
        map.insert(name, path);
    }
    map
}

// 运行时生成DLL文件
pub fn generate_dll(filename: &str, buf: &[u8]) -> io::Result<(String, String)> {
    let mut p = set_current_dir();
    p.push(filename);
    let mut f = File::create(&p).unwrap();
    f.write(&buf).unwrap();
    Ok((
        filename.to_string(),
        p.to_str().unwrap_or_default().to_string(),
    ))
}

fn set_current_dir() -> PathBuf {
    let tmp_dir = {
        let mut path = dirs::data_dir().unwrap();
        path.push("股票行情观察");
        path.push("运行库");
        path
    };
    if !tmp_dir.exists() {
        create_dir_all(tmp_dir.clone()).unwrap();
    }
    // info!("current_dir={:?}", tmp_dir);
    if let Err(err) = env::set_current_dir(tmp_dir.clone()) {
        println!("当前工作文件夹设置失败:{:?}", err);
    }
    tmp_dir
}
